package com.supersoul.myself.controller;

import com.alibaba.fastjson.JSONObject;
import com.supersoul.myself.cache.TokenCache;
import com.supersoul.myself.entity.Blog;
import com.supersoul.myself.entity.Comment;
import com.supersoul.myself.entity.User;
import com.supersoul.myself.ex.ServiceException;
import com.supersoul.myself.service.CommentService;
import com.supersoul.myself.util.PageVO;
import com.supersoul.myself.util.R;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private TokenCache tokenCache;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/save")
    public R saveComment(@RequestBody @Valid Comment comment, HttpServletRequest request) throws ServiceException {
        String token = request.getHeader("token");
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(tokenJson, User.class);
        String id = commentService.saveComment(comment, user);
        return R.success(id);
    }

    @GetMapping("/detail/{blogId}")
    public R getBlog(@PathVariable("blogId") @NotEmpty  String blogId, PageVO pageVO) throws ServiceException {
        Page<Comment> commentPage = commentService.getBlog(blogId, pageVO);
        return R.success(commentPage);
    }
}
